package com.uziot.boot.jetty;


import lombok.extern.slf4j.Slf4j;
import org.mortbay.jetty.Server;
import org.mortbay.jetty.nio.SelectChannelConnector;
import org.mortbay.jetty.servlet.ServletHandler;
import org.mortbay.jetty.servlet.ServletHolder;
import org.mortbay.thread.QueuedThreadPool;

/**
 * @author shidt
 * @version V1.0
 * @className JettyHttpServer
 * @date 2022-03-11 00:07:45
 * @description
 */

@Slf4j
public class JettyHttpServer implements Runnable {

    private volatile boolean run = false;
    private boolean reset = true;

    final private QueuedThreadPool threadPool = new QueuedThreadPool();
    final private SelectChannelConnector connector = new SelectChannelConnector();

    @Override
    public void run() {
        try {
            ServletHandler handler = new ServletHandler();
            ServletHolder servletHolder = handler.addServletWithMapping(JettyServlet.class, "/hello");
            servletHolder.setInitOrder(2);
            servletHolder.setInitParameter("encoding", "UTF-8");
            Server server = new Server();
            server.setThreadPool(threadPool);
            // 因为8080被spring容器使用了
            this.connector.setPort(8081);
            server.addConnector(connector);

            server.addHandler(handler);
            try {
                server.start();
                log.info("Jetty Server 启动........");
            } catch (Exception e) {
                throw new IllegalStateException("Failed to start jetty server because: " + e.getMessage(), e);
            }
            if (log.isInfoEnabled()) {
                log.info("Jetty connector startup success!");
            }
        } catch (Exception e) {
            if (log.isErrorEnabled()) {
                log.error("connector error:", e);
            }
            if (reset && run) {
                synchronized (this) {
                    try {
                        wait(500);
                    } catch (InterruptedException e1) {
                        e1.printStackTrace();
                    }
                }
                run();
            }
        }
    }

    /**
     * 停止JETTY端口
     */
    public void stop() {
        try {
            this.connector.close();
            this.threadPool.stop();
        } catch (Throwable e) {
            log.error(e.getMessage(), e);
        }
        run = false;
    }

    public boolean isReset() {
        return reset;
    }

    public void setReset(boolean reset) {
        this.reset = reset;
    }
}